package com.wonders.ghy.juc.自旋锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 题目：实现一个自旋锁
 * 自旋锁的好处：循环比较直到成功为止，没有类似wait的阻塞
 *
 * 通过CAS操作完成自旋锁，A线程先进来调用myLock方法自己持有锁5秒钟，B随后进来
 * 后发现当前线程持有锁，不是null，所以只能通过自旋等待，知道A释放锁后B随后抢到
 *
 */
public class SpinLockDemo {
    // 原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    private void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"  准备开始尝试获取锁");
        while (!atomicReference.compareAndSet(null,thread)){
            //System.out.println(thread.getName()+"  尝试获取锁");
        }
        System.out.println(thread.getName()+" 获得了锁");
    }

    private void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"  invoke myUnLock");
    }
    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            spinLockDemo.myLock();
            // 暂停一会线程
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.unlock();
        },"AA").start();

        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            spinLockDemo.myLock();
            spinLockDemo.unlock();
        },"BB").start();
    }
}
